/*
 * Copyright (c) 2020, chao
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-08-19     chao         the first version
 */

#include <rtthread.h>
#include "xpt2046.h"
#include "xpt2046_calibration.h"
#include "touch.h"

rt_thread_t xpt2046_thread;
rt_device_t touch_device;
struct rt_touch_data *touch_data;

void xpt2046_thread_entry(void *parameter)
{
    uint16_t logX, logY;
    
    while(1)
    {
        rt_device_read(touch_device, 0, touch_data, 1);

        if (touch_data->event == RT_TOUCH_EVENT_DOWN)
        {
            logX = xpt_caculate_log_x(touch_data->x_coordinate);
            logY = xpt_caculate_log_y(touch_data->y_coordinate);
            //rt_kprintf("(%4d, %4d) -> (%4d, %4d)\n", touch_data->x_coordinate, touch_data->y_coordinate, logX, logY);
        }
        rt_thread_delay(20);
    }
}

int xpt2046_example(void)
{
    struct rt_touch_info info;
    
    rt_hw_xpt2046_init("touch");
    xpt2046_calibration_init();

    touch_device = rt_device_find("touch");

    rt_device_open(touch_device, RT_DEVICE_FLAG_RDONLY);

    rt_device_control(touch_device, RT_TOUCH_CTRL_GET_INFO, &info);
    rt_kprintf("type       :%d\n", info.type);
    rt_kprintf("vendor     :%d\n", info.vendor);
    rt_kprintf("point_num  :%d\n", info.point_num);
    rt_kprintf("range_x    :%d\n", info.range_x);
    rt_kprintf("range_y    :%d\n", info.range_y);

    touch_data = (struct rt_touch_data *)rt_calloc(1, sizeof(struct rt_touch_data));
#if 0
    xpt2046_thread = rt_thread_create("touch", xpt2046_thread_entry, RT_NULL, 1024, 10, 20);
    if (xpt2046_thread == RT_NULL)
    {
        rt_kprintf("create xpt2046 thread error\n");

        return -RT_ENOMEM;
    }
    rt_thread_startup(xpt2046_thread);
#endif
    return RT_EOK;
}
INIT_APP_EXPORT(xpt2046_example);

uint8_t xpt_data_get(int *x, int *y)
{
#if 1
    rt_device_read(touch_device, 0, touch_data, 1);
    
    if (touch_data->event == RT_TOUCH_EVENT_DOWN)
    {
        //rt_kprintf("(%4d, %4d) -> (%4d, %4d)\n", touch_data->x_coordinate, touch_data->y_coordinate, 
        //xpt_caculate_log_x(touch_data->x_coordinate), xpt_caculate_log_y(touch_data->y_coordinate));
    }
#endif
    *x = xpt_caculate_log_x(touch_data->x_coordinate);
    *y = xpt_caculate_log_y(touch_data->y_coordinate);
    return touch_data->event;
}


